<template>
  <div class="check-manager">
    <ACard class="statistics-card">
      <div class="statistics">
        <AStatistic
          title="待审核帖子"
          :value="pendingPosts.length"
          :valueStyle="{ color: pendingPosts.length > 0 ? '#ff4d4f' : '#52c41a' }"
        >
          <template #prefix>
            <FileSearchOutlined />
          </template>
        </AStatistic>
      </div>
    </ACard>

    <ACard class="table-card" title="待审核帖子列表">
      <div class="table-toolbar">
        <div class="left-actions">
          <AButton type="primary" @click="fetchPendingPosts">
            <ReloadOutlined />
            刷新列表
          </AButton>
        </div>
        <div class="right-actions">
          <AInput.Search
            placeholder="搜索帖子内容"
            style="width: 250px"
            @search="onSearch"
            allowClear
          />
        </div>
      </div>

      <ATable
        :columns="columns"
        :data-source="filteredPosts"
        :loading="loading"
        :scroll="{ x: 1200 }"
        :row-key="(record: PendingPost) => record.id"
        :pagination="{
          showSizeChanger: true,
          showTotal: (total) => `共 ${total} 条`,
          defaultPageSize: 10,
          pageSizeOptions: ['10', '20', '50'],
        }"
        :rowClassName="getRowClassName"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'id'">
            <span class="id-column">#{{ record.id }}</span>
          </template>

          <template v-if="column.dataIndex === 'authorName'">
            <div class="author-cell">
              <AImage
                :src="record.authorAvatar || '/default-avatar.png'"
                :fallback="'/default-avatar.png'"
                :width="32"
                :height="32"
                :preview="false"
                :style="{ borderRadius: '50%' }"
              />
              <span>{{ record.authorName }}</span>
            </div>
          </template>

          <template v-if="column.dataIndex === 'title'">
            <div class="title-cell">
              <div class="title-text">{{ record.title || '无标题' }}</div>
              <div v-if="record.isAnonymous === 1" class="anonymous-tag">
                <ATag color="orange">匿名</ATag>
              </div>
            </div>
          </template>

          <template v-if="column.dataIndex === 'content'">
            <div class="content-cell">{{ record.content }}</div>
          </template>

          <template v-if="column.dataIndex === 'type'">
            <ATag :color="postTypes[record.type]?.color">
              {{ postTypes[record.type]?.text || '未知' }}
            </ATag>
          </template>

          <template v-if="column.dataIndex === 'createTime'">
            <div class="time-cell">
              <div>{{ formatDate(record.createTime, 'date') }}</div>
              <div class="time-detail">{{ formatDate(record.createTime, 'time') }}</div>
            </div>
          </template>

          <template v-if="column.key === 'action'">
            <div class="action-buttons">
              <AButton type="link" @click="handleView(record as PendingPost)">
                <EyeOutlined />
                查看
              </AButton>
              <AButton type="primary" size="small" @click="handleApprove(record as PendingPost)">
                <CheckOutlined />
                通过
              </AButton>
              <AButton type="primary" danger size="small" @click="showRejectModal(record.id)">
                <CloseOutlined />
                拒绝
              </AButton>
            </div>
          </template>
        </template>

        <template #emptyText>
          <AEmpty description="暂无待审核的帖子" />
        </template>
      </ATable>
    </ACard>

    <AModal
      v-model:visible="rejectModalVisible"
      title="拒绝原因"
      @ok="handleReject"
      okText="确认"
      cancelText="取消"
      :okButtonProps="{ danger: true }"
    >
      <AInput.TextArea
        v-model:value="rejectReason"
        placeholder="请输入拒绝原因"
        :rows="4"
        :maxlength="200"
        show-count
      />
    </AModal>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import {
  Card as ACard,
  Table as ATable,
  Tag as ATag,
  Button as AButton,
  Image as AImage,
  Modal as AModal,
  Input as AInput,
  message,
  Empty as AEmpty,
  Statistic as AStatistic,
} from 'ant-design-vue'
import {
  CheckOutlined,
  CloseOutlined,
  EyeOutlined,
  FileSearchOutlined,
  ReloadOutlined,
} from '@ant-design/icons-vue'
import { getPendingPosts, approvePost, rejectPost } from '@/api/manger'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import type { TableColumnsType } from 'ant-design-vue'

interface PendingPost {
  id: number
  authorId: number
  authorName: string
  authorAvatar: string
  title: string
  content: string
  type: number
  isAnonymous: number
  createTime: string
  updateTime: string
  viewsCount: number
  commentsCount: number
  likesCount: number
  collectsCount: number
}

const router = useRouter()
const userStore = useUserStore()
const loading = ref(false)
const pendingPosts = ref<PendingPost[]>([])
const rejectModalVisible = ref(false)
const rejectReason = ref('')
const currentPostId = ref<number | null>(null)
const searchText = ref('')

// 帖子类型映射
const postTypes: Record<number, { text: string; color: string }> = {
  0: { text: '其他', color: '' },
  1: { text: '公告', color: 'red' },
  2: { text: '活动', color: 'blue' },
  3: { text: '求助', color: 'orange' },
  4: { text: '二手交易', color: 'green' },
  5: { text: '表白', color: 'pink' },
  6: { text: '失物招领', color: 'purple' },
  7: { text: '校园咨询', color: 'cyan' },
  8: { text: '吐槽', color: 'volcano' },
  9: { text: '学习', color: 'geekblue' },
  10: { text: '反馈与建议', color: 'gold' },
}

const columns: TableColumnsType<PendingPost> = [
  {
    title: 'ID',
    dataIndex: 'id',
    width: 80,
    sorter: (a, b) => a.id - b.id,
  },
  {
    title: '作者',
    dataIndex: 'authorName',
    width: 150,
  },
  {
    title: '标题',
    dataIndex: 'title',
    width: 200,
  },
  {
    title: '内容',
    dataIndex: 'content',
    ellipsis: true,
    width: 300,
  },
  {
    title: '类型',
    dataIndex: 'type',
    width: 120,
    filters: Object.entries(postTypes).map(([key, value]) => ({
      text: value.text,
      value: Number(key),
    })),
    onFilter: (value, record) => record.type === value,
  },
  {
    title: '发布时间',
    dataIndex: 'createTime',
    width: 180,
    sorter: (a, b) => new Date(a.createTime).getTime() - new Date(b.createTime).getTime(),
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right',
  },
]

// 过滤后的帖子列表
const filteredPosts = computed(() => {
  if (!searchText.value) return pendingPosts.value

  return pendingPosts.value.filter(
    (post) =>
      post.title?.toLowerCase().includes(searchText.value.toLowerCase()) ||
      post.content?.toLowerCase().includes(searchText.value.toLowerCase()),
  )
})

const fetchPendingPosts = async () => {
  try {
    loading.value = true
    const res = await getPendingPosts()
    if (res.data.code === 200) {
      pendingPosts.value = res.data.data
    }
  } catch (error) {
    console.error('获取待审核帖子列表失败:', error)
    message.error('获取待审核帖子列表失败')
  } finally {
    loading.value = false
  }
}

const handleView = (record: PendingPost) => {
  // 将帖子信息存储到 localStorage，以便在详情页面使用
  localStorage.setItem('pendingPostId', record.id.toString())
  router.push(`/post/${record.id}?from=check`)
}

const handleApprove = async (record: PendingPost) => {
  const adminId = userStore.userInfo?.id
  if (!adminId) {
    message.error('获取管理员信息失败')
    return
  }

  try {
    const res = await approvePost(record.id, adminId)
    if (res.data.code === 200) {
      message.success('审核通过')
      fetchPendingPosts()
    }
  } catch (error) {
    console.error('审核操作失败:', error)
    message.error('审核操作失败')
  }
}

const showRejectModal = (postId: number) => {
  currentPostId.value = postId
  rejectReason.value = ''
  rejectModalVisible.value = true
}

const handleReject = async () => {
  if (!rejectReason.value.trim()) {
    message.error('请输入拒绝原因')
    return
  }

  const adminId = userStore.userInfo?.id
  if (!adminId || !currentPostId.value) {
    message.error('获取信息失败')
    return
  }

  try {
    const res = await rejectPost(currentPostId.value, adminId, rejectReason.value.trim())
    if (res.data.code === 200) {
      message.success('已拒绝通过')
      rejectModalVisible.value = false
      fetchPendingPosts()
    }
  } catch (error) {
    console.error('拒绝操作失败:', error)
    message.error('拒绝操作失败')
  }
}

const formatDate = (dateStr: string, type: 'date' | 'time' | 'full' = 'full') => {
  const date = new Date(dateStr)
  if (type === 'date') {
    return date.toLocaleDateString()
  } else if (type === 'time') {
    return date.toLocaleTimeString()
  }
  return date.toLocaleString()
}

const onSearch = (value: string) => {
  searchText.value = value
}

const getRowClassName = (record: PendingPost) => {
  // 根据帖子类型或其他条件设置行样式
  return record.isAnonymous === 1 ? 'anonymous-row' : ''
}

onMounted(() => {
  fetchPendingPosts()
})
</script>

<style scoped>
.check-manager {
  padding: 24px;
}

.statistics-card {
  margin-bottom: 24px;
  background: linear-gradient(to right, #fff9f9, #f6ffed);
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.statistics {
  display: flex;
  gap: 48px;
  padding: 12px;
}

.table-card {
  min-height: 500px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.table-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.author-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.title-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.title-text {
  font-weight: 500;
}

.content-cell {
  color: #666;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.time-cell {
  font-size: 13px;
}

.time-detail {
  color: #999;
  font-size: 12px;
  margin-top: 4px;
}

.action-buttons {
  display: flex;
  align-items: center;
  gap: 8px;
  white-space: nowrap;
}

.id-column {
  color: #999;
  font-family: monospace;
}

:deep(.ant-table-cell) {
  vertical-align: middle;
  padding: 12px 16px;
}

:deep(.ant-card-head) {
  border-bottom: 1px solid #f0f0f0;
  padding: 0 24px;
}

:deep(.ant-card-head-title) {
  font-size: 16px;
  font-weight: 500;
}

:deep(.ant-statistic-title) {
  font-size: 16px;
  margin-bottom: 8px;
}

:deep(.ant-statistic-content) {
  font-size: 28px;
  font-weight: bold;
}

:deep(.ant-table-thead > tr > th) {
  background-color: #fafafa;
  font-weight: 500;
}

:deep(.ant-table-row:hover) {
  background-color: #f5f5f5;
}

:deep(.anonymous-row) {
  background-color: #fffbe6;
}

:deep(.ant-table-row-expand-icon-cell) {
  width: 50px;
}

:deep(.ant-table-pagination.ant-pagination) {
  margin: 16px 0;
}

:deep(.ant-empty) {
  margin: 32px 0;
}
</style>
